package openjdk.future;

import java.util.concurrent.*;

/**
 * Created by boot on 1/8/16.
 */
public class CompletionSvc {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        CompletionService<Integer> cs = new ExecutorCompletionService<Integer>(executorService);

        for (int i = 0; i < 5; i++) {
            final int taskId = i;
            cs.submit(new Callable<Integer>() {
                public Integer call() throws Exception {
                    return taskId;
                }
            });
        }
        for (int i = 1; i < 5; i++) {
            try {
                Thread.sleep(300);
                System.out.println(cs.take().get());
            } catch (InterruptedException ie) {
                ie.printStackTrace();
            } catch (ExecutionException ee) {
                ee.printStackTrace();
            } finally {
                executorService.shutdown();
            }
        }
    }
}
